package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.vo.SecKillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_PREFIX = "seckill:session:";
    private final String SKUKILL_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    /**
     * blockHandler只处理资源流控，fallback处理所有异常
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
        long time = new Date().getTime();
        try(Entry entry = SphU.entry("seckillSkus")){
            Set<String> keys = redisTemplate.keys(SESSIONS_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSIONS_PREFIX, "");
                String[] s = replace.split("_");
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);
                if (time >= start && time <= end) {
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_PREFIX);
                    List<String> list = ops.multiGet(range);
                    if (list != null) {
                        List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                            SecKillSkuRedisTo to = JSON.parseObject(item.toString(), SecKillSkuRedisTo.class);
                            //to.setRandomCode(null);
                            return to;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        }catch (BlockException e){
            log.error("seckillSkus资源被限流");
        }
        return null;
    }

    public List<SecKillSkuRedisTo> blockHandler(){
        log.error("getCurrentSeckillSkusResource资源被限流");
        return null;
    }

    @Override
    public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_PREFIX);
        Set<String> keys = ops.keys();

        if (keys != null && keys.size() > 0) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String json = ops.get(key);
                    SecKillSkuRedisTo to = JSON.parseObject(json, SecKillSkuRedisTo.class);
                    long now = new Date().getTime();
                    if (now < to.getStartTime() || now > to.getEndTime()) {
                        to.setRandomCode(null);
                    }
                    return to;
                }
            }
        }
        return null;
    }

    @Override
    public void uploadSedkillSku() {
        //扫描最近三天需要参与秒杀的活动
        R r = couponFeignService.getLatesDaySession();
        if (r.getCode() == 0) {
            List<SeckillSessionsWithSkus> sessionDatas = (List<SeckillSessionsWithSkus>) r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //缓存活动信息
            saveSessionInfos(sessionDatas);
            //缓存活动的关联商品信息
            saveSessionSkuInfos(sessionDatas);
        }
    }

    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessionDatas) {
        sessionDatas.stream().forEach(session -> {
            Long start = session.getStartTime().getTime();
            Long end = session.getEndTime().getTime();
            String key = SESSIONS_PREFIX + start + "_" + end;
            List<String> skuIds = session.getRelationSkus().stream().map(item -> {
                return item.getPromotionSessionId() + "_" + item.getSkuId().toString();
            }).collect(Collectors.toList());
            if (!redisTemplate.hasKey(key)) {
                redisTemplate.opsForList().leftPushAll(key, skuIds);
            }
        });
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessionDatas) {
        sessionDatas.stream().forEach(session -> {
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_PREFIX);
            session.getRelationSkus().stream().forEach(sku -> {
                String randomCode = UUID.randomUUID().toString().replace("-", "");
                String key = sku.getPromotionSessionId() + "_" + sku.getSkuId().toString();
                if (!redisTemplate.hasKey(key)) {
                    SecKillSkuRedisTo to = new SecKillSkuRedisTo();
                    to.setStartTime(session.getStartTime().getTime());
                    to.setEndTime(session.getEndTime().getTime());
                    to.setSeckillLimit(new BigDecimal(1));
                    //sku基本信息
                    R r = productFeignService.getSkuInfo(sku.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo skuInfo = (SkuInfoVo) r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        to.setSkuInfo(skuInfo);
                    }
                    //sku秒杀信息
                    BeanUtils.copyProperties(sku, to);
                    //随机码
                    to.setRandomCode(randomCode);
                    ops.put(key, JSON.toJSONString(to));

                    //信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                    semaphore.trySetPermits(sku.getSeckillCount().intValue());
                }
            });
        });
    }

    @Override
    public String secKill(String killId, String key, Integer num) {
        //获取当前商品信息
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_PREFIX);
        String s = ops.get(killId);
        if (StringUtils.isEmpty(s)) {
            return null;
        }
        SecKillSkuRedisTo to = JSON.parseObject(s, SecKillSkuRedisTo.class);
        //校验是否在秒杀时间
        Long start = to.getStartTime();
        Long end = to.getEndTime();
        Long now = new Date().getTime();
        if (now < start || now > end) {
            return null;
        }
        //校验随机码和skuId
        String randomCode = to.getRandomCode();
        String id = to.getPromotionSessionId() + "_" + to.getSkuId();
        if (!randomCode.equals(key) || !killId.equals(id)) {
            return null;
        }
        //验证购物数量是否合理
        int limit = to.getSeckillLimit() == null ? 1 : to.getSeckillLimit().intValue();
        if (num > limit) {
            return null;
        }
        //验证这个人是否已经买过
        MemberRespVo memberRespVo = LoginInterceptor.threadLocal.get();
        String ukey = memberRespVo.getId() + "_" + id;
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(ukey, num.toString(), end - now, TimeUnit.MILLISECONDS);
        if (!aBoolean) {//占位失败，表示已经买过
            return null;
        }
        //拿到信号量就成功
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
        boolean b = semaphore.tryAcquire(num);
//        try {
//            b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        if (!b) {
            return null;
        }
        //发送消息 秒杀成功
        String orderSn = IdWorker.getTimeId();
        SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
        seckillOrderTo.setOrderSn(orderSn);
        seckillOrderTo.setPromotionSessionId(to.getPromotionSessionId());
        seckillOrderTo.setMemberId(memberRespVo.getId());
        seckillOrderTo.setSkuId(to.getSkuId());
        seckillOrderTo.setSeckillPrice(to.getSeckillPrice());
        seckillOrderTo.setNum(num);
        rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);
        return orderSn;
    }
}
